﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using DynamicExpression = System.Linq.Dynamic.DynamicExpression;

namespace FaceSharp.MVC.Tests.Code
{
    public static class LinqExtensions
    {
        public static IQueryable SelectMany(this IQueryable source, string selector, params object[] values)
        {
            if (source == null)
                throw new ArgumentNullException("source");
            if (selector == null)
                throw new ArgumentNullException("selector");

            // Parse the lambda
            var lambda = DynamicExpression.ParseLambda(source.ElementType, null, selector, values);

            // Fix lambda by recreating to be of correct Func<> type in case 
            // the expression parsed to something other than IEnumerable<T>.
            // For instance, a expression evaluating to List<T> would result 
            // in a lambda of type Func<T, List<T>> when we need one of type
            // an Func<T, IEnumerable<T> in order to call SelectMany().
            Type inputType = source.Expression.Type.GetGenericArguments()[0];
            Type resultType = lambda.Body.Type.GetGenericArguments()[0];
            Type enumerableType = typeof(IEnumerable<>).MakeGenericType(resultType);
            Type delegateType = typeof(Func<,>).MakeGenericType(inputType, enumerableType);
            lambda = Expression.Lambda(delegateType, lambda.Body, lambda.Parameters);

            // Create the new query
            return source.Provider.CreateQuery(
                Expression.Call(
                    typeof(Queryable), "SelectMany",
                    new Type[] { source.ElementType, resultType },
                    source.Expression, Expression.Quote(lambda)));
        }

    }
}
